#!/usr/bin/env perl

#do some experiments on processing time of queries and usage of approximative heuristic

use Util;
use Scorer;
use QueryProcessor;
use Time::HiRes;

my $scorer = Scorer->new(maxRMSD=>5);
my $queryProcessor = QueryProcessor->new(pathCofm=>"/home/bq_pharth/scop_only/", scorer=>$scorer);

my @queries = getQueries("/home/bq_pharth/candidates");
print "total complexes ",scalar(@queries),"\n";

my $l = 1;
for my $q (@queries){
	
	$l++;
	my @qDoms = Util::getDomains($q, "/home/bq_pharth/scop_only/");
	next if scalar(@qDoms)>30;
	my @cds = getCandidates("/home/bq_pharth/candidates",$q);
	for(my $i=0; $i<scalar(@cds); $i++){
		my $c=$cds[$i];
		my @cDoms = Util::getDomains($c, "/home/bq_pharth/scop_only/");
		open FILE, ">>./measurement3" or die $!;
		print FILE ($q," ",$c," ");
		print $q," ",$c," ";
		print FILE (scalar(@qDoms)," ",scalar(@cDoms)," ");
		print scalar(@qDoms)," ",scalar(@cDoms),"\n";
		next if scalar(@cDoms)>30;
		my $t1 = Time::HiRes::time()," ";
		
		my @results = getAllResults(inf, $q, $c);
		
		my $dt=Time::HiRes::time()-$t1;
		print FILE (sprintf("%.3f",$dt)," ");
		
		if(scalar(@results) != 0){
			my $s = $results[scalar(@results)-1];
			print FILE ($s->numberOfDomains," ");
		} else {
			print FILE (0," ");
		}
		print FILE (scalar(@results)," ");
		my $appr = $queryProcessor->approximative();
		print FILE ($appr,$/);
		
		last if $i >=3;
		close FILE;
	}
	last if $l>=1000;
}




#executes the query loop, until Query Processor signals finished
sub getAllResults{
	my($mergeOps, $q, $c)=@_;
	$queryProcessor->reset();
	my @results=();
	my $l=1;
	while($l){
		my ($anotherQueryNeeded, @subcomplexes) = $queryProcessor->query($q,$c,inf,inf,50);
		push @results, @subcomplexes;
		$l = $anotherQueryNeeded;
	}
	return @results;
}


sub getQueries{
	my ($pathCandidates)= @_;
	my @queries = ();
	open FILE, $pathCandidates or die "candidate file could not be opened";
	while(my $line=<FILE>){
		if($line =~ /---/){
			push @queries, substr($line,3,4);
		};
	}
	close FILE; 	
	return @queries;
}


sub getCandidates{
	my ($pathCandidates, $pdbID)= @_;
	my @candidates = ();
	open FILE, $pathCandidates or die "candidate file could not be opened";
	while(my $line=<FILE>){
		last if ($line =~ /---$pdbID---/);
	}
	if(my $line=<FILE>){
		my @columns = split(/ +/,$line);
		pop(@columns); #remove last element, which is "\n" and not a pdbID
		for my $column (@columns){
			$column =~ s/\n//;
			push @candidates, $column;
		}
	} else {
		die "$query pdbID not in precomputed candidate file";
	}
	close FILE; 	
	return @candidates;
}